var commonjs = require("../../../utils/common.js");
var app = getApp();


// 常量，不能改变
var CONS_ACTION_REFRESH = "refresh";
var CONS_ACTION_LOADMORE = "loadmore";
var CONS_PAGE_SIZE = 21;

//变量
var requestSuccess = false;
var action = CONS_ACTION_REFRESH;
var page = 0;
var category = "";

Page({
  data: {
    movies: []
  },
  onLoad: function (options) {
    category = options.category;
    wx.setNavigationBarTitle({
      title: category
    });
    commonjs.showLoadingToast();
    action = CONS_ACTION_REFRESH;
    this.requestDoubanMovieDatas();
  },
  onPullDownRefresh() {
    action = CONS_ACTION_REFRESH;
    page = 0;
    this.requestDoubanMovieDatas();
  },
  onReachBottom() {
    if (requestSuccess) {
      ++page;
    }
    action = CONS_ACTION_LOADMORE;
    commonjs.showLoadingToast();
    this.requestDoubanMovieDatas();
  },
  // 根据category的不同来请求豆瓣电影数据
  requestDoubanMovieDatas() {
    var requestUrl = app.globalDatas.doubanBaseUrl;
    switch (category) {
      case "正在上映的电影-北京":
        requestUrl += "v2/movie/in_theaters?count=" + CONS_PAGE_SIZE + "&start=" + page;
        break;
      case "即将上映的电影":
        requestUrl += "v2/movie/coming_soon?count=" + CONS_PAGE_SIZE + "&start=" + page;
        break;
      case "豆瓣电影Top250":
        requestUrl += "v2/movie/top250?count=" + CONS_PAGE_SIZE + "&start=" + page;
        break;
      default:
        console.error("This category is not supported ");
    }

    var that = this;
    commonjs.http(requestUrl, function (data) {
      requestSuccess = true;
      if (action === CONS_ACTION_REFRESH) {
        wx.stopPullDownRefresh();
        // 清空旧数据
        that.setData({movies:[]});
      } else if (action === CONS_ACTION_LOADMORE) {
        wx.hideToast();
      }
      that.processDoubanData(data)
    }, function () {
      requestSuccess = false;
      if (action === CONS_ACTION_REFRESH) {
          wx.stopPullDownRefresh();
          that.setData({movies:[]});
      } else if (action === CONS_ACTION_LOADMORE) {
          wx.hideToast();
          commonjs.showNetworkError();
      }
    });
  },
  // 处理豆瓣返回的数据，转换成需要的数据
  processDoubanData(data) {
    var subjects = data.subjects;
    var movies = this.data.movies;
    for (var i = 0; i < subjects.length; i++) {
      var subject = subjects[i];
      var movie = {};
      movie["movieId"] = subject.id;
      movie["cover"] = subject.images.large;
      movie["title"] = subject.title;
      movie["rating"] = { stars: commonjs.convertStarsToStarsArray(subject.rating.stars), average: subject.rating.average };
      movies.push(movie);
    }
    this.setData({ movies: movies });
  },
  onItemClick(event) {
    var movieId = event.currentTarget.dataset.movieId;
    wx.navigateTo({
      url: '../movie-detail/movie-detail?movieId=' + movieId
    });
  }
})